/**
 * 操作用户信息处理模块
 */
const Sequelize = require('sequelize')
const sequelize = require('../db/dbconfig')
const UserModel = require('../db/models/users')
const userModel = UserModel(sequelize)
const Op = Sequelize.Op

// 添加用户模块
exports.addUserinfo = async (req, res) => {
  try {
    const userinfo = req.body
    // 判断 username 是否存在
    let is_exist = await userModel.findOne({
      attributes: ['user_id'],
      where: {
        username: userinfo.username
      }
    })
    // console.log(is_exist);
    if (is_exist) return res.myMsg('用户名已存在')
    let userNickname = 'user' + Math.floor(Math.random() * 9000 + 1000)
    userinfo.nickname = userinfo.nickname === '' ? userNickname : userinfo.nickname
    let results = await userModel.create({
      username: userinfo.username,
      password: userinfo.password,
      nickname: userinfo.nickname,
      email: userinfo.email,
      permissions: userinfo.permissions,
      sex: userinfo.sex
    })
    if (results === null) return res.myMsg('服务器内部错误，添加失败')
    res.myMsg(results, 0)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg(e, 500)
  }
}

// 删除用户信息
exports.deleteUserinfo = async (req, res) => {
  try {
    let results = await userModel.update({
      is_delete: 1
    }, {
      where: {
        user_id: req.query.id
      }
    })
    if (results[0] !== 1) return res.myMsg('删除失败,用户不存在', 500)
    return res.myMsg('删除成功', 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }
}

// 封禁用户
exports.banUserinfoOrdinary = async (req, res) => {
  try {
    let results = await userModel.update({
      is_ban: 1
    }, {
      where: {
        user_id: req.body.user_id,
        permissions: 1,
        is_delete: 0,
      }
    })
    if (results[0] !== 1) return res.myMsg('封禁失败,用户不合法', 500)
    return res.myMsg('封禁成功', 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }
}

// 解除封禁用户
exports.banUserinfoOrdinaryCancel = async (req, res) => {
  try {
    let results = await userModel.update({
      is_ban: 0
    }, {
      where: {
        user_id: req.body.user_id,
        permissions: 1,
        is_delete: 0,
      }
    })
    if (results[0] !== 1) return res.myMsg('解封失败,用户不合法', 500)
    return res.myMsg('解封成功', 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }
}

// 修改用户信息
exports.updateUserinfo = async (req, res) => {
  try {
    const userinfo = req.body
    let is_exist = await userModel.findOne({
      where: {
        user_id: userinfo.user_id
      }
    })
    if (is_exist === null) return res.myMsg('用户不存在')
    // console.log('------------------');
    // console.log(is_exist);
    // console.log(userinfo);
    // console.log('------------------');
    let results = await userModel.update({
      password: userinfo.password === '' ? is_exist.password : userinfo.password,
      nickname: userinfo.nickname === '' ? is_exist.nickname : userinfo.nickname,
      email: userinfo.email === '' ? is_exist.email : userinfo.email,
      sex: userinfo.sex === '' ? is_exist.sex : userinfo.sex,
      user_biography: userinfo.user_biography === '' ? is_exist.user_biography : userinfo.user_biography,
      credit: userinfo.credit === '' ? is_exist.credit : userinfo.credit,
      permissions: userinfo.permissions === '' ? is_exist.permissions : userinfo.permissions
    }, {
      where: {
        user_id: userinfo.user_id
      }
    })
    if (results === '') return res.myMsg('修改失败', 1)
    res.myMsg('修改成功', 0)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }
}

// 获取全部用户信息
exports.getUserinfoAll = async (req, res) => {
  // const offset = parseInt(req.params.offset)%2===0 ? parseInt(req.params.offset):parseInt(req.params.offset)-1
  try {
    let offset = 0
    let results = await userModel.findAndCountAll({
      where: {
        is_delete: 0
      },
      order: [
        ['user_id', 'asc']
      ],
      limit: 10,
      offset
    })
    // console.log(results.count,results.rows.map(blog => blog.dataValues))
    if (results === '') return res.myMsg('查询错误')
    for (let result of results.rows) {
      result.dataValues.password = ''
    }
    res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg(e, 500)
  }
}

// 查询全部普通用户
exports.getUserinfoOrdinary = async (req, res) => {
  // const offset = parseInt(req.params.offset)%2===0 ? parseInt(req.params.offset):parseInt(req.params.offset)-1
  try {
    let offset = 0
    let results = await userModel.findAndCountAll({
      where: {
        is_delete: 0,
        permissions: 1,
      },
      order: [
        ['user_id', 'asc']
      ],
      limit: 10,
      offset
    })
    // console.log(results.count,results.rows.map(blog => blog.dataValues))
    if (results === '') return res.myMsg('查询错误', 500)
    for (let result of results.rows) {
      result.dataValues.password = ''
    }
    return res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg(e, 500)
  }
}

// 获取用户信息byUsername
exports.getUserinfoByUsername = async (req, res) => {
  try {
    const userinfo = req.query
    let results = await userModel.findOne({
      where: {
        is_delete: 0,
        username: userinfo.username
      }
    })
    if (results === null) return res.myMsg('查询失败,不存在该用户')
    results.password = '';
    res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }

}

// 获取用户信息byNickname模糊查询
exports.getUserinfoByNickname = async (req, res) => {
  try {
    const userinfo = req.body.nickname
    let results = await userModel.findAll({
      where: {
        is_delete: 0,
        nickname: {
          [Op.like]: `%${userinfo}%`
        }
      }
    })
    // console.log(results)
    if (results == '') return res.myMsg('查询失败，不存在该用户')
    for (let result of results) {
      result.dataValues.password = ''
    }
    res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg(e, 500)
  }
}

exports.getUserinfo = async (req, res) => {
  const user = req.auth
  // try {
  //   jwt.verify(token, seccret, (error, decoded) => {
  //     if (error) {
  //       console.log(error)
  //       return error
  //     }
  //     console.log("校验", decoded)
  //   })
  // } catch (error) {

  // }
  res.send({
    data: user
  })
}

// 修改用户头像
exports.updateUserPic = async (req, res) => {
  try {
    const userinfo = req.body
    let results = await userModel.findOne({
      where: {
        is_delete: 0,
        username: userinfo.username
      }
    })
    if (results === null) return res.myMsg('用户不存在', 500)
    let updateinfo = await userModel.update({
      user_pic: userinfo.user_pic === '' ? results.user_pic : userinfo.user_pic,
    }, {
      where: {
        username: userinfo.username
      }
    })
    if(updateinfo === '') return res.myMsg('修改失败', 500)
    res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误', 500)
  }
}